<template>
   <el-cascader
    ref="cascader"
    v-model="valueTitle" :disabled="disabled" :clearable="clearable" @clear="clearHandle"
    :props="props"
    :size="size"
    collapse-tags
     @change="handleChange"
    :options="valueData">
  </el-cascader>
</template>

<script>
export default {
  name: 'el-tree-select',
  props: {
    /* 配置项 */
    props: {
      type: Object,
      default: () => {
        return {
          multiple: true,
          expandTrigger: 'hover',
          value: 'id',             // ID字段名
          label: 'name',         // 显示名称
          children: 'childNodes'    // 子级字段名
        }
      }
    },
     /* 选项列表数据(树形结构的对象数组) */
    list: {
      type: Array,
      default: () => { return null }
    },
    /* 初始值 */
    value: {
      type: String,
      default: () => { return null }
    },
    /* 初始值 */
    url: {
      type: String,
      default: () => { return '/sys/area/treeData' }
    },
    disabled: {
      type: Boolean,
      dafault: () => { return false }
    },
    showCheckbox: {
      type: Boolean,
      dafault: () => { return false }
    },
    /* 初始值 */
    label: {
      type: String,
      default: () => { return null }
    },
    /* 可清空选项 */
    clearable: {
      type: Boolean,
      default: () => { return true }
    },
    size: {
      type: String,
      default: () => { return 'default' }
    },
    /* 自动收起 */
    accordion: {
      type: Boolean,
      default: () => { return false }
    },
    extend: {
      type: Array,
      default: () => { return null }
    }
  },
  data () {
    return {
      valueTitle: [],
      valueData: []
    }
  },
  created () {
    if(this.url && this.url != '') {
      this.$http({
        url: this.url,
        method: 'get'
      }).then(({data}) => {
        this.valueData = data.treeData
        if(this.extend) {
          this.valueData = this.valueData.concat(this.extend)
        }
        if (this.value) {
          this.valueTitle = this.value.split('/')
        }
      })
    } else {
      this.valueData = this.valueData.concat(this.extend)
    }
  },
  methods: {
    // 切换选项
    handleChange (node) {
      var labels = this.$refs.cascader.getCheckedNodes(true).map(item => {
        return item.label
      }).join(',')
      this.$emit('getValue', this.valueTitle.join('/'), labels)
    },
    // 清除选中
    clearHandle () {
      this.valueTitle = ''
      this.$emit('getValue', null, '')
    },
    /* 清空选中样式 */
    clearSelected () {
      let allNode = document.querySelectorAll('#tree-option .el-tree-node')
      allNode.forEach((element) => element.classList.remove('is-current'))
    }
  },
  watch: {
    value () {
      if (this.value === '') {
        this.clearHandle()
      } else if (this.value) {
        this.valueTitle = this.value.split('/')
      }
    }
  }
}
</script>
